﻿using B.S.ProcessEgine.API.Applocations.Commands.FormInfoCommand;
using B.S.ProcessEgine.ErrorCode;
using B.S.ProcessEgine.Infractructure.Interfaces;
using MediatR;

namespace B.S.ProcessEgine.API.Applocations.CommandHandlers.FormInfohandler
{

    public class DeleteFormCommandHandler : IRequestHandler<DeleteFormCommand, ApiResult>
    {

        private readonly IFormInfoRepository _formRepository;
        private readonly ILogger<DeleteFormCommandHandler> _logger;

        public DeleteFormCommandHandler(IFormInfoRepository formRepository, ILogger<DeleteFormCommandHandler> logger)
        {
            _formRepository = formRepository;
            _logger = logger;
        }

        public async Task<ApiResult> Handle(DeleteFormCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var form = await _formRepository.GetAsync(x => x.FormId == request.FormId && !x.IsDel);
                if (form == null)
                {
                    return ApiResult.Fail("对象不存在", StateCodeEnum.Fail);
                }

                //删除表单
                form.IsDel = true;

                //更新表单
                var result = await _formRepository.UpdateAsync(form);

                return result > 0 ? ApiResult.Success(StateCodeEnum.Ok) : ApiResult.Fail("删除表单失败", StateCodeEnum.Fail);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "DeleteFormCommandHandler Error");
                return ApiResult.Fail("删除表单异常", StateCodeEnum.Exception);
            }
        }
    }
}
